#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

class Solution {
public:
    int threeSumClosest(vector<int>& nums, int target) {
        sort(nums.begin(), nums.end());

        int ret = INT_MAX;
        for (int i = nums.size() - 1; i >= 2; --i) {
            int l = 0, r = i - 1;
            while (l < r) {
                int sum = nums[l] + nums[r] + nums[i];
                if (abs(ret - target) > abs(sum - target)) {
                    ret = sum;
                    ++l;
                }
                else if (abs(ret - target) < abs(sum - target)) {
                    --r;
                }
                else {
                    ret = sum;
                    break;
                }
            }
        }

        return ret;
    }
};

int main()
{
    vector<int> nums = { 1,1,1,1 };
    int target = -100;
    cout << Solution().threeSumClosest(nums, target);

    return 0;
}